
#include "board.h"
#include <rthw.h>
#include <rtthread.h>
#include "driv_eth.h"
#include <string.h>

#include "lwip/opt.h"

#include "lwip/opt.h"
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include "lwip/netif.h"
#include "lwip/stats.h"
#include "lwip/tcpip.h"
#include "lwip/dhcp.h"
#include "lwip/netifapi.h"
#include "lwip/dns.h"
#include "netif/etharp.h"

#include "lwip/inet.h"


#define HW_RECEIVE_MSG_MAIL_BOX_SIZE 10
static rt_mailbox_t  ETH_HwRxMsg_Done = NULL;

ETH_HandleTypeDef heth;


void ETH_ReceiveMssgInit(void)
{
    ETH_HwRxMsg_Done = rt_mb_create("eth_rec",HW_RECEIVE_MSG_MAIL_BOX_SIZE,0);
}

void ETH_ReceiveMssgIndicate(rt_uint32_t msg)
{
    if(ETH_HwRxMsg_Done != NULL)
    {
        rt_mb_send(ETH_HwRxMsg_Done,(rt_ubase_t)msg);
    }
}

int ETH_HwFetchMssg(rt_uint32_t* msg)
{
    if(ETH_HwRxMsg_Done == NULL)
    {
        *msg = ETH_HW_NO_INITIALIZATION;
    }
    else
    {
        rt_mb_recv(ETH_HwRxMsg_Done,(rt_ubase_t*)msg,RT_WAITING_FOREVER);
    }
    return 0;

}







struct pbuf *stm32_eth_rx(void)
{

    struct pbuf *p = NULL;
    struct pbuf *q = NULL;
    HAL_StatusTypeDef state;
    uint16_t len = 0;
    uint8_t *buffer;
    __IO ETH_DMADescTypeDef *dmarxdesc;
    uint32_t bufferoffset = 0;
    uint32_t payloadoffset = 0;
    uint32_t byteslefttocopy = 0;
    uint32_t i = 0;

    
//    if(!netif_is_link_up(&EMAC_if))
//    {
//        return NULL;
//    }
    
    /* Get received frame */
    state = HAL_ETH_GetReceivedFrame_IT(&heth);
    if (state != HAL_OK)
    {
        //LOG_D("receive frame faild");
        return NULL;
    }

    /* Obtain the size of the packet and put it into the "len" variable. */
    len = heth.RxFrameInfos.length;
    buffer = (uint8_t *)heth.RxFrameInfos.buffer;

    //LOG_D("receive frame len : %d", len);

    if (len > 0)
    {
        /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */
        p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
    }

#ifdef ETH_RX_DUMP
    dump_hex(buffer, p->tot_len);
#endif

    if (p != NULL)
    {
        dmarxdesc = heth.RxFrameInfos.FSRxDesc;
        bufferoffset = 0;
        for (q = p; q != NULL; q = q->next)
        {
            byteslefttocopy = q->len;
            payloadoffset = 0;

            /* Check if the length of bytes to copy in current pbuf is bigger than Rx buffer size*/
            while ((byteslefttocopy + bufferoffset) > ETH_RX_BUF_SIZE)
            {
                /* Copy data to pbuf */
                memcpy((uint8_t *)((uint8_t *)q->payload + payloadoffset), (uint8_t *)((uint8_t *)buffer + bufferoffset), (ETH_RX_BUF_SIZE - bufferoffset));

                /* Point to next descriptor */
                dmarxdesc = (ETH_DMADescTypeDef *)(dmarxdesc->Buffer2NextDescAddr);
                buffer = (uint8_t *)(dmarxdesc->Buffer1Addr);

                byteslefttocopy = byteslefttocopy - (ETH_RX_BUF_SIZE - bufferoffset);
                payloadoffset = payloadoffset + (ETH_RX_BUF_SIZE - bufferoffset);
                bufferoffset = 0;
            }
            /* Copy remaining data in pbuf */
            memcpy((uint8_t *)((uint8_t *)q->payload + payloadoffset), (uint8_t *)((uint8_t *)buffer + bufferoffset), byteslefttocopy);
            bufferoffset = bufferoffset + byteslefttocopy;
        }
    }

    /* Release descriptors to DMA */
    /* Point to first descriptor */
    dmarxdesc = heth.RxFrameInfos.FSRxDesc;
    /* Set Own bit in Rx descriptors: gives the buffers back to DMA */
    for (i = 0; i < heth.RxFrameInfos.SegCount; i++)
    {
        dmarxdesc->Status |= ETH_DMARXDESC_OWN;
        dmarxdesc = (ETH_DMADescTypeDef *)(dmarxdesc->Buffer2NextDescAddr);
    }

    /* Clear Segment_Count */
    heth.RxFrameInfos.SegCount = 0;

    /* When Rx Buffer unavailable flag is set: clear it and resume reception */
    if ((heth.Instance->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET)
    {
        /* Clear RBUS ETHERNET DMA flag */
        heth.Instance->DMASR = ETH_DMASR_RBUS;
        /* Resume DMA reception */
        heth.Instance->DMARPDR = 0;
    }

    return p;
}


err_t stm32_eth_tx(struct pbuf *p)
{
    err_t ret = ERR_MEM;
    HAL_StatusTypeDef state;
    struct pbuf *q;
    uint8_t *buffer = (uint8_t *)(heth.TxDesc->Buffer1Addr);
    __IO ETH_DMADescTypeDef *DmaTxDesc;
    uint32_t framelength = 0;
    uint32_t bufferoffset = 0;
    uint32_t byteslefttocopy = 0;
    uint32_t payloadoffset = 0;

    DmaTxDesc = heth.TxDesc;
    bufferoffset = 0;

//    if(!netif_is_link_up(&EMAC_if))
//    {
//        return ERR_IF;
//    }
//    
    /* copy frame from pbufs to driver buffers */
    for (q = p; q != NULL; q = q->next)
    {
        /* Is this buffer available? If not, goto error */
        if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET)
        {
            //LOG_D("buffer not valid");
            ret = ERR_USE;
            goto error;
        }

        /* Get bytes in current lwIP buffer */
        byteslefttocopy = q->len;
        payloadoffset = 0;

        /* Check if the length of data to copy is bigger than Tx buffer size*/
        while ((byteslefttocopy + bufferoffset) > ETH_TX_BUF_SIZE)
        {
            /* Copy data to Tx buffer*/
            memcpy((uint8_t *)((uint8_t *)buffer + bufferoffset), (uint8_t *)((uint8_t *)q->payload + payloadoffset), (ETH_TX_BUF_SIZE - bufferoffset));

            /* Point to next descriptor */
            DmaTxDesc = (ETH_DMADescTypeDef *)(DmaTxDesc->Buffer2NextDescAddr);

            /* Check if the buffer is available */
            if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET)
            {
                //LOG_E("dma tx desc buffer is not valid");
                ret = ERR_USE;
                goto error;
            }

            buffer = (uint8_t *)(DmaTxDesc->Buffer1Addr);

            byteslefttocopy = byteslefttocopy - (ETH_TX_BUF_SIZE - bufferoffset);
            payloadoffset = payloadoffset + (ETH_TX_BUF_SIZE - bufferoffset);
            framelength = framelength + (ETH_TX_BUF_SIZE - bufferoffset);
            bufferoffset = 0;
        }

        /* Copy the remaining bytes */
        memcpy((uint8_t *)((uint8_t *)buffer + bufferoffset), (uint8_t *)((uint8_t *)q->payload + payloadoffset), byteslefttocopy);
        bufferoffset = bufferoffset + byteslefttocopy;
        framelength = framelength + byteslefttocopy;
    }

#ifdef ETH_TX_DUMP
    dump_hex(buffer, p->tot_len);
#endif

    /* Prepare transmit descriptors to give to DMA */
    /* TODO Optimize data send speed*/
    //LOG_D("transmit frame lenth :%d", framelength);

    /* wait for unlocked */
    while (heth.Lock == HAL_LOCKED);

    state = HAL_ETH_TransmitFrame(&heth, framelength);
    if (state != HAL_OK)
    {
        //LOG_E("eth transmit frame faild: %d", state);
    }

    ret = ERR_OK;

error:

    /* When Transmit Underflow flag is set, clear it and issue a Transmit Poll Demand to resume transmission */
    if ((heth.Instance->DMASR & ETH_DMASR_TUS) != (uint32_t)RESET)
    {
        /* Clear TUS ETHERNET DMA flag */
        heth.Instance->DMASR = ETH_DMASR_TUS;

        /* Resume DMA transmission*/
        heth.Instance->DMATPDR = 0;
    }

    return ret;
}



static int check_eth_network_change(void)
{
    static int status_old = 0;
    int status,ret;

    status = (netif_is_up(netif_default)&&(netif_default->ip_addr.addr!=0)) ;
    if(status != status_old)
    {
        status_old = status;
        ret = 1;
    }
    else
    {
        ret = 0;
    }
    return ret;

}

void list_if(void)
{
    uint32_t index;
    struct netif * netif;

    netif = netif_list;

    while( netif != RT_NULL )
    {
        rt_kprintf("network interface: %c%c%s\n",
                   netif->name[0],
                   netif->name[1],
                   (netif == netif_default)?" (Default)":"");
        rt_kprintf("MTU: %d\n", netif->mtu);
        rt_kprintf("MAC: ");
        for (index = 0; index < netif->hwaddr_len; index ++)
            rt_kprintf("%02x ", netif->hwaddr[index]);
        rt_kprintf("\nFLAGS:");
        if (netif->flags & NETIF_FLAG_UP) rt_kprintf(" UP");
        else rt_kprintf(" DOWN");
        if (netif->flags & NETIF_FLAG_LINK_UP) rt_kprintf(" LINK_UP");
        else rt_kprintf(" LINK_DOWN");
        if (netif->flags & NETIF_FLAG_ETHARP) rt_kprintf(" ETHARP");
        if (netif->flags & NETIF_FLAG_BROADCAST) rt_kprintf(" BROADCAST");
        if (netif->flags & NETIF_FLAG_IGMP) rt_kprintf(" IGMP");
        rt_kprintf("\n");
        rt_kprintf("ip address: %s\n", ipaddr_ntoa(&(netif->ip_addr)));
        rt_kprintf("gw address: %s\n", ipaddr_ntoa(&(netif->gw)));
        rt_kprintf("net mask  : %s\n", ipaddr_ntoa(&(netif->netmask)));
        netif = netif->next;
    }

    {
        const ip_addr_t *ip_addr;

        for(index=0; index<DNS_MAX_SERVERS; index++)
        {
            ip_addr = dns_getserver(index);
            rt_kprintf("dns server #%d: %s\n", index, ipaddr_ntoa(ip_addr));
        }
    }

}

MSH_CMD_EXPORT(list_if, list network interface information);




#define PHY_BASIC_STATUS_REG        0x01U
#define PHY_LINKED_STATUS_MASK      (1<<2)
#define PHY_AUTONEGO_COMPLETE_MASK  (1<<5)

#define PHY_BASIC_CONTROL_REG       0x00U
#define PHY_RESET_MASK              (1<<15)
#define PHY_AUTO_NEGOTIATION_MASK   (1<<12)

#if 0
#define PHY_DEBUG rt_kprintf
#else
#define PHY_DEBUG(...)
#endif

void ETH_PhyMonitorTask(void *parameter)
{
    uint32_t SR;
    uint8_t link_status=0,link_status_new;
    uint8_t detected_count;

    while (1)
    {
        HAL_ETH_ReadPHYRegister(&heth, PHY_BASIC_STATUS_REG, (uint32_t *)&SR);
        PHY_DEBUG("PHY BASIC STATUS REG:0x%04X \n", SR);

        link_status_new = (SR & PHY_LINKED_STATUS_MASK)?1:0;
        if( link_status !=  link_status_new)
        {
            link_status = link_status_new;
            if(link_status)
            {
                rt_kprintf("\nLAN Plugged!\n");
                HAL_ETH_WritePHYRegister(&heth, PHY_BASIC_CONTROL_REG, PHY_RESET_MASK);
                rt_thread_delay(1000);
                HAL_ETH_WritePHYRegister(&heth, PHY_BASIC_CONTROL_REG, PHY_AUTO_NEGOTIATION_MASK);
                detected_count = 0;

                while(detected_count < 200)
                {
                    HAL_ETH_ReadPHYRegister(&heth, PHY_BASIC_STATUS_REG, (uint32_t *)&SR);
                    rt_thread_delay(1000);
                    if(SR&PHY_AUTONEGO_COMPLETE_MASK)
                    {
                        break;
                    }
                    detected_count ++;
                }
                
                if(detected_count<200)
                {
                    HAL_ETH_ReadPHYRegister(&heth, PHY_SR, (uint32_t *)&SR);
                    PHY_DEBUG("PHY STATUS REG:0x%04X \n", SR);
                    if(SR & PHY_LINK_STATUS)
                    {
                        rt_kprintf("LAN LINK UP: ");
                        if (SR & PHY_SPEED_STATUS)
                        {
                            rt_kprintf("10Mbps ");
                        }
                        else
                        {
                            rt_kprintf("100Mbps ");
                        }

                        if (SR & PHY_DUPLEX_STATUS)
                        {
                            rt_kprintf("Full-duplex\n");
                        }
                        else
                        {
                            rt_kprintf("Half-duplex\n");
                        }
                        ETH_ReceiveMssgIndicate(ETH_HW_MSG_LINKED_UP);
                    }
                    else
                    {
                        rt_kprintf("PHY ERROR : LINK_UP.\n");
                        link_status = 0;
                        ETH_ReceiveMssgIndicate(ETH_HW_MSG_LINKED_DOWN);
                        HAL_ETH_WritePHYRegister(&heth, PHY_BASIC_CONTROL_REG, PHY_RESET_MASK);
                        rt_thread_delay(2000);
                    }
                }
                else
                {
                    rt_kprintf("PHY ERROR : AUTO_NEGOTIATION.\n");
                    link_status = 0;
                    ETH_ReceiveMssgIndicate(ETH_HW_MSG_LINKED_DOWN);
                    HAL_ETH_WritePHYRegister(&heth, PHY_BASIC_CONTROL_REG, PHY_RESET_MASK);
                    rt_thread_delay(2000);
                }

            }
            else
            {
                rt_kprintf("LAN Unplugged!\n");
                rt_kprintf("LAN LINK DOWN\n");
                ETH_ReceiveMssgIndicate(ETH_HW_MSG_LINKED_DOWN);
            }
        }
        
        if(check_eth_network_change())
        {
            list_if();
        }
        
        rt_thread_delay(1000);
    }
}






/**
  * @brief ETH Initialization Function
  * @param None
  * @retval None
  */

__align(8) static ETH_DMADescTypeDef DMARxDscrTab[ETH_RXBUFNB], DMATxDscrTab[ETH_TXBUFNB];
__align(8) static uint8_t Rx_Buff[ETH_RXBUFNB*ETH_MAX_PACKET_SIZE];
__align(8) static uint8_t Tx_Buff[ETH_TXBUFNB*ETH_MAX_PACKET_SIZE];

void ETH_ReceivePacketTask(void* p);
uint8_t ETHLocalMacAddr[6];

void stm32_eth_init(void)
{

    rt_thread_t tid;
    
    ETHLocalMacAddr[0] = 0x0C;
//    ETHLocalMacAddr[1] = ConfigFlashArea.SysInfo.serial_number[7];
//    ETHLocalMacAddr[2] = ConfigFlashArea.SysInfo.serial_number[8];
    ETHLocalMacAddr[1] = *(uint8_t *)(UID_BASE + 8);
    ETHLocalMacAddr[2] = *(uint8_t *)(UID_BASE + 6);
    ETHLocalMacAddr[3] = *(uint8_t *)(UID_BASE + 4);
    ETHLocalMacAddr[4] = *(uint8_t *)(UID_BASE + 2);
    ETHLocalMacAddr[5] = *(uint8_t *)(UID_BASE + 0);
    /* USER CODE END ETH_Init 1 */
    heth.Instance = ETH;
    heth.Init.MACAddr = ETHLocalMacAddr;
    heth.Init.PhyAddress = DP83848_PHY_ADDRESS;
    heth.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE;
    heth.Init.Speed = ETH_SPEED_100M;
    heth.Init.DuplexMode = ETH_MODE_FULLDUPLEX;
    heth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;
    heth.Init.RxMode = ETH_RXINTERRUPT_MODE;
    heth.Init.ChecksumMode = ETH_CHECKSUM_BY_SOFTWARE;

  /* USER CODE BEGIN MACADDRESS */
    
  /* USER CODE END MACADDRESS */
    HAL_ETH_DeInit(&heth);
    if (HAL_ETH_Init(&heth) != HAL_OK)
    {
        Error_Handler();
    }
  /* USER CODE BEGIN ETH_Init 2 */
    /* Initialize Tx Descriptors list: Chain Mode */
    HAL_ETH_DMATxDescListInit(&heth, DMATxDscrTab, Tx_Buff, ETH_TXBUFNB);

    /* Initialize Rx Descriptors list: Chain Mode  */
    HAL_ETH_DMARxDescListInit(&heth, DMARxDscrTab, Rx_Buff, ETH_RXBUFNB);

//    /* ETH interrupt Init */
//    HAL_NVIC_SetPriority(ETH_IRQn, 0, 0);
//    HAL_NVIC_EnableIRQ(ETH_IRQn);

    /* Enable MAC and DMA transmission and reception */
    if (HAL_ETH_Start(&heth) != HAL_OK)
    {
        Error_Handler();
    }
    
    /* USER CODE END ETH_Init 2 */
    ETH_ReceiveMssgInit();
    
    tid = rt_thread_create("eth_phy",ETH_PhyMonitorTask,0,256,10,10);
    RT_ASSERT(tid != RT_NULL);
    rt_thread_startup(tid);
    
    tid = rt_thread_create("eth_rec",ETH_ReceivePacketTask,0,4096,10,10);
    RT_ASSERT(tid != RT_NULL);
    rt_thread_startup(tid);
    
}



void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth)
{
    ETH_ReceiveMssgIndicate(ETH_HW_MSG_RECEIVE);
}

void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth)
{
    while(1)
    {
    }
}


void LAN_LowPowerMode(void)
{
    HAL_GPIO_WritePin(ETH_CTRL_GPIO_Port,ETH_CTRL_Pin,GPIO_PIN_RESET);
}

void LAN_NormalMode(void)
{
    HAL_GPIO_WritePin(ETH_CTRL_GPIO_Port,ETH_CTRL_Pin,GPIO_PIN_SET);
}

void LAN_PhyReset(void)
{
    
    HAL_GPIO_WritePin(ETH_RST_GPIO_Port,ETH_RST_Pin,GPIO_PIN_RESET);
    rt_hw_us_delay(10);
    HAL_GPIO_WritePin(ETH_RST_GPIO_Port,ETH_RST_Pin,GPIO_PIN_SET);
    rt_hw_us_delay(10);
    
}


void HAL_ETH_MspInit(ETH_HandleTypeDef* heth)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(heth->Instance==ETH)
  {
  /* USER CODE BEGIN ETH_MspInit 0 */

  /* USER CODE END ETH_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ETH_CLK_ENABLE();
  
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    /**ETH GPIO Configuration    
    PC1     ------> ETH_MDC
    PA1     ------> ETH_REF_CLK
    PA2     ------> ETH_MDIO
    PA7     ------> ETH_CRS_DV
    PC4     ------> ETH_RXD0
    PC5     ------> ETH_RXD1
    PB11     ------> ETH_TX_EN
    PB12     ------> ETH_TXD0
    PB13     ------> ETH_TXD1 
    */
    GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* ETH interrupt Init */
    HAL_NVIC_SetPriority(ETH_IRQn, 1, 2);
    HAL_NVIC_EnableIRQ(ETH_IRQn);
  /* USER CODE BEGIN ETH_MspInit 1 */

  /* USER CODE END ETH_MspInit 1 */
  }

}


void ETH_IRQHandler(void)
{
    rt_interrupt_enter();
    HAL_ETH_IRQHandler(&heth);
    rt_interrupt_leave();

}


